package yxy.cherry.data.dfa;

import java.util.ArrayList;

/** 关键词搜索DFA算法 */
public class Dfa {
	private WordNode rootNode = new WordNode();

	public void addWord(String word) {
		if (word.length() <= 0) {
			return;
		}
		char[] chs = word.toCharArray();
		WordNode node = null;
		for (int i = 0, end = chs.length - 1; i <= end; i++) {
			Character ch = chs[i];
			if (i == 0) {
				node = rootNode.getSubNode(ch);
				if (node == null) {
					if (i == end) {
						rootNode.addEnd(ch);
					} else {
						node = rootNode.addChar(ch);
					}
				}
				continue;
			}
			if (i == end) {
				node.addEnd(ch);
			} else {
				node = node.addChar(ch);
			}
		}
	}

	/** 判断前word需做整形 */
	public boolean isSensitive(String word) {
		word = word.toLowerCase();
		if (word.length() <= 0) {
			return false;
		}
		ArrayList<Character> checkedList = new ArrayList<>();
		char[] chs = word.toCharArray();
		for (int i = 0, end = chs.length - 1; i <= end; i++) {
			Character ch = chs[i];
			if (checkedList.contains(ch)) {
				continue;
			}
			WordNode node = rootNode.getSubNode(ch);
			if (node == null) {
				continue;
			}
			if (isSensitive(node, chs, i)) {
				return true;
			}
			checkedList.add(ch);
		}
		return false;
	}

	private boolean isSensitive(WordNode node, char[] chs, int start) {
		if (node.isEnd()) {
			return true;
		}
		for (int i = start + 1, end = chs.length - 1; i <= end; i++) {
			Character ch = chs[i];
			WordNode sub = node.getSubNode(ch);
			if (sub == null) {
				continue;
			}
			if (sub.isEnd()) {
				return true;
			}
			if (isSensitive(sub, chs, i)) {
				return true;
			}
		}
		return node.isEnd();
	}

	@Override
	public String toString() {
		return rootNode.toString();
	}
}
